﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MapControl;

namespace GPSMap
{
    public partial class frmGPSMap_Old : Form
    {
        private List<GPSPoint> gpsdata;

        private MapControl.ucMap mapControl;
        public frmGPSMap_Old()
        {
            InitializeComponent();
            //Load Map            
            mapControl = new ucMap();
            this.splitContainer1.Panel2.Controls.Add(mapControl);
            mapControl.Dock = DockStyle.Fill;

            InitTestGPSData();
        }

        ////public void AddDemoData()
        ////{
        ////    DataTable source = new DataTable();
        ////    source.Columns.Add("Num", typeof(string));
        ////    source.Columns.Add("Name", typeof (string));
        ////    source.Columns.Add("Lon", typeof(string));
        ////    source.Columns.Add("Lat", typeof(string));
        ////    source.Columns.Add("Alt", typeof(string));
        ////    source.Columns.Add("Speed", typeof(string));
        ////    source.Columns.Add("Angle", typeof(string));

        ////    dataGridViewGPS.DataSource = source;
        ////    dataGridViewGPS.Columns[0].Width = 50;
        ////    dataGridViewGPS.Columns[1].Width = 100;
        ////    dataGridViewGPS.Columns[2].Width = 100;

        ////    DataRow row = source.NewRow();
        ////    row.ItemArray = new object[] { "1", "Heli1", "106.719604", "10.854886","1000","156","314"};
        ////    source.Rows.Add(row);

        ////    row = source.NewRow();
        ////    row.ItemArray = new object[] { "2", "Heli1", "106.89929", "10.72808", "1200", "150", "214" };
        ////    source.Rows.Add(row);

        ////    row = source.NewRow();
        ////    row.ItemArray = new object[] { "3", "Heli1", "107.741203", "10.876465", "1400", "166", "114" };
        ////    source.Rows.Add(row);

        ////    row = source.NewRow();
        ////    row.ItemArray = new object[] { "4", "Heli1", "107.75219", "12.189704", "1600", "196", "14" };
        ////    source.Rows.Add(row);

        ////    row = source.NewRow();
        ////    row.ItemArray = new object[] { "5", "Heli1", "108.211899", "15.855674", "1800", "186", "45" };
        ////    source.Rows.Add(row);

        ////    row = source.NewRow();
        ////    row.ItemArray = new object[] { "6", "Heli1", "105.355453", "20.07657", "2000", "176", "180" };
        ////    source.Rows.Add(row);
            
        ////}

        private void frmGPSMap_Load(object sender, EventArgs e)
        {
            //AddDemoData();
            xPanderPanelList1.Width = 200;

            string[] bigSquareArray = new string[10];// { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            bigSquareArray[0] = txtBigSquare1.Text;
            bigSquareArray[1] = txtBigSquare2.Text;
            bigSquareArray[2] = txtBigSquare3.Text;
            bigSquareArray[3] = txtBigSquare4.Text;
            bigSquareArray[4] = txtBigSquare5.Text;
            bigSquareArray[5] = txtBigSquare6.Text;
            bigSquareArray[6] = txtBigSquare7.Text;
            bigSquareArray[7] = txtBigSquare8.Text;
            bigSquareArray[8] = txtBigSquare9.Text;
            bigSquareArray[9] = txtBigSquare10.Text;
            mapControl.Coord9x9.BigSquareArray = bigSquareArray;
        }


        private void checkBoxShowCoordinate9x9_CheckedChanged(object sender, EventArgs e)
        {
            mapControl.ShowCoordinate9x9 = checkBoxShowCoordinate9x9.Checked;
            mapControl.Refresh();
        }

        //private void dataGridViewGPS_SelectionChanged(object sender, EventArgs e)
        //{
        //    if (dataGridViewGPS.CurrentRow != null)
        //    {
        //        string name = dataGridViewGPS.CurrentRow.Cells["Name"].Value.ToString();
        //        double lon = double.Parse(dataGridViewGPS.CurrentRow.Cells["Lon"].Value.ToString());
        //        double lat = double.Parse(dataGridViewGPS.CurrentRow.Cells["Lat"].Value.ToString());
        //        double alt = double.Parse(dataGridViewGPS.CurrentRow.Cells["Alt"].Value.ToString());
        //        double speed = double.Parse(dataGridViewGPS.CurrentRow.Cells["Speed"].Value.ToString());
        //        double angle = double.Parse(dataGridViewGPS.CurrentRow.Cells["Angle"].Value.ToString());
        //        mapControl.SetGPSCoord(name, lon, lat, alt, speed, angle);
        //        mapControl.Map.ZoomTo(mapControl.Map.Zoom, lon, lat);
        //    }
        //}

        private void btnLayers_Click(object sender, EventArgs e)
        {
            if (mapControl.Map.Layers.LayersDlg(null,null))
            {
                
            }
        }

        private void txtBigSquare1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // OpenFileDialog folder = new OpenFileDialog(); 
            //MapXLib.Layer templayer = new MapXLib.Layer(); 
            MapXLib.Layer templayer;
            MapXLib.LayerInfo liinfo;
            liinfo = new MapXLib.LayerInfoClass();
            //MapXLib.Layer lyr = axMap1.Layers._Item("WORLD"); 
            MapXLib.Fields flds = new MapXLib.FieldsClass();
            MapXLib.Field fld = null;
            MapXLib.Dataset dfs = null;
            //MapXLib.Theme the = new MapXLib.Theme(); 


            // templayer = axMap1.Layers.CreateLayer("templayer",null,1,32);      
            // if (openFile.ShowDialog() == DialogResult.OK) 
            //if (open.ShowDialog() == DialogResult.OK) 
            // { 
            //  axMap1.Layers.Add(openFile.FileName, 0);//Ä¬ÈÏÖµÎª0£¬C#µ÷ÓÃ²»ÄÜÊ¡ÂÔÄ¬ÈÏÖµ£¬Í¼²ãµÄÎ»ÖÃ 
            //} 

            liinfo.Type = MapXLib.LayerInfoTypeConstants.miLayerInfoTypeTab;
            //string sfile = openFile.InitialDirectory;
            string path = @"f:\Programming\2013\B1MV\Project\GPSMap\GPSMap\bin\Debug\Maps\";
            // liinfo.AddParameter("openFile.FileName"); 
            liinfo.AddParameter("Visible", true);
            liinfo.AddParameter("AutoCreateDataset", true);
            liinfo.AddParameter("datasetname", "layername");
            liinfo.AddParameter("filespec", path + "Hoangsa.TAB");
            flds.Add("Country", "Country", MapXLib.AggregationFunctionConstants.miAggregationSum, MapXLib.FieldTypeConstants.miTypeString);
            flds.Add("Capital", "Capital", MapXLib.AggregationFunctionConstants.miAggregationSum, MapXLib.FieldTypeConstants.miTypeString);
            flds.Add("Contient", "Contient", MapXLib.AggregationFunctionConstants.miAggregationSum, MapXLib.FieldTypeConstants.miTypeString);
            // dfs = axMap1.DataSets.Add(MapXLib.DatasetTypeConstants.miDataSetLayer,   , 0, 0, 0, flds, false); 
            mapControl.Map.Layers.Add(liinfo, 0);

            // the = axMap1.DataSets.Add(MapXLib.DatasetTypeConstants.miDataSetLayer);    
            mapControl.Map.Layers.LayersDlg("", "");
            
            //liinfo[1, 1];  
            // the.ThemeDlg("", "");   

            // liinfo.AddParameter ("filespec",+filepath + layername + ".TAB"); 
            //  liinfo.AddParameter( "AutoCreateDataset",true); 
            //  liinfo.AddParameter ("datasetname",layername );     

            /* string sfile; 
             openFile.Filter = "mapinfo tables(*.tab)|*.tab"; 
             openFile.FileName = ""; 
  
             OpenFileDialog folder = new OpenFileDialog(); 
             folder.AddExtension = true; 
             folder.CheckFileExists = true; 
             folder.CheckPathExists = true; 
             folder.Filter = "mapinfo tables(*.tab)|*.tab"; 
             folder.FileName = ""; 
             if (folder.ShowDialog() == DialogResult.OK) 
             { 
                 MapXLib.LayerInfo li; 
                 li = new MapXLib.LayerInfoClass(); 
                 li.Type = MapXLib.LayerInfoTypeConstants.miLayerInfoTypeTab; 
 
                 li.AddParameter("folder.Filename"); 
                 li.AddParameter("visible", false); 
                 li.AddParameter("autocreatedataset", true); 
                 li.AddParameter("datasetname", "mylayer"); 
                 axMap1.Layers.Add(li, 0); 
                 axMap1.Layers.LayersDlg("", ""); 
 
 
             } 
             */
            /*if (folder.ShowDialog() == DialogResult.OK) 
 
            { 
                MapXLib.Feature tu = new MapXLib.Feature(); 
                tu.Attach(axMap1.GetOcx());    
                sfile = openFile.FileName ;  
                axMap1.Layers.Add sfile ;  
            }*/
            // axMap1.Layers.Add  ;   
        }

        private void button2_Click(object sender, EventArgs e)
        {
           mapControl.Map.DisplayCoordSys.PickCoordSys(null, null);
           mapControl.Map.NumericCoordSys = mapControl.Map.DisplayCoordSys; 
        }

        private void checkBoxShowRoutes_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void btnSaveGeoSet_Click(object sender, EventArgs e)
        {
            mapControl.Map.Layers.Remove("Symbols");
            mapControl.Map.SaveMapAsGeoset("BanDo", "E:\\Temp\\bando.gst");
            mapControl.Map.Layers.AddUserDrawLayer("Symbols", 1);
        }

        private void dataGridViewTestGPS_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private DataTable dbTestGPS;
        private void InitTestGPSData()
        {
            mapControl.AxMap_MouseDownEvent += new AxMapXLib.CMapXEvents_MouseDownEventHandler(AxMap_MouseDownEvent);
            mapControl.AxMap_DrawUserLayer += new AxMapXLib.CMapXEvents_DrawUserLayerEventHandler(AxMap_DrawUserLayer);
            
            gpsdata = new List<GPSPoint>();
            dbTestGPS = new DataTable();
            dbTestGPS.Columns.Add("LocalTime", typeof(string));
            dbTestGPS.Columns.Add("Name", typeof (string));
            dbTestGPS.Columns.Add("Lon", typeof(string));
            dbTestGPS.Columns.Add("Lat", typeof(string));
            dbTestGPS.Columns.Add("Alt", typeof(string));
            dbTestGPS.Columns.Add("Speed", typeof(string));
            dbTestGPS.Columns.Add("Angle", typeof(string));
            dataGridViewTestGPSData.DataSource = dbTestGPS;

        }
        private bool isStartTestGPSData = false;
        private void btnTest_Click(object sender, EventArgs e)
        {
            
            isStartTestGPSData = !isStartTestGPSData;
            if (isStartTestGPSData)
            {
                btnTest.Text = "Stop Test";
            }
            else
            {
                btnTest.Text = "Start Test";
            }
        }


        public void AxMap_MouseDownEvent(object sender, AxMapXLib.CMapXEvents_MouseDownEvent e)
        {
            PointF pScreen = new PointF(e.x, e.y);
            if (e.button == 1)
            {
                //Nếu là đang thêm dữ liệu mới
                if (isStartTestGPSData)
                {
                    mapControl.Map.CurrentTool = MapXLib.ToolConstants.miArrowTool;
                    
                    //Hiển thị tọa độ Longitude, Latitude
                    double lon, lat;
                    lon = lat = 0;
                    mapControl.Map.ConvertCoord(ref e.x, ref e.y, ref lon, ref lat, MapXLib.ConversionConstants.miScreenToMap);
                    
                    DataRow row = dbTestGPS.NewRow();
                    Random ran = new Random();
                    row.ItemArray = new object[] { DateTime.Now.ToString(), "Heli1", lon.ToString(), lat.ToString(), ran.Next(2000, 3000).ToString(), ran.Next(200, 400).ToString(), ran.Next(0, 360).ToString() };
                    dbTestGPS.Rows.Add(row);
                    mapControl.Map.Refresh();
                }
                else //Nếu đang chọn xem thông tin gps data
                {
                    foreach (DataGridViewRow row in dataGridViewTestGPSData.Rows)
                    {
                        GPSPoint objGPS = GetGPSData(row);
                        //Nếu click trúng vào vị trí GPS thì hiển thị form
                        if (objGPS.HitTest(pScreen) == 0 && 
                            mapControl.Map.CurrentTool == MapXLib.ToolConstants.miArrowTool)
                        {
                            row.Selected = true;
                            currGPSData = objGPS;
                            mapControl.Refresh();
                            string result = string.Format("Name={0}\nLongitude={1}\nLatitude={2}\nAltitude={3}\nSpeed={4}\nAngle={5}",
                                objGPS.Name,
                                objGPS.LonGPS.ToString(),
                                objGPS.LatGPS.ToString(),
                                objGPS.Alt.ToString(),
                                objGPS.Speed.ToString(),
                                objGPS.Angle.ToString()
                                );
                            MessageBox.Show(result);
                        }
                    }

                }
            }
        }

        public GPSPoint GetGPSData(DataGridViewRow row)
        {
            string name = row.Cells["Name"].Value.ToString();
            DateTime localTime = DateTime.Parse(row.Cells["LocalTime"].Value.ToString());
            double lon = double.Parse(row.Cells["Lon"].Value.ToString());
            double lat = double.Parse(row.Cells["Lat"].Value.ToString());
            double alt = double.Parse(row.Cells["Alt"].Value.ToString());
            double speed = double.Parse(row.Cells["Speed"].Value.ToString());
            double angle = double.Parse(row.Cells["Angle"].Value.ToString());
            GPSPoint obj = new GPSPoint(mapControl.Map, name, localTime, lon, lat, alt, speed, angle);
            
            return obj;
        }

        public void AxMap_DrawUserLayer(object sender, AxMapXLib.CMapXEvents_DrawUserLayerEvent e)
        {
            Graphics g = Graphics.FromHdc(new IntPtr(e.hOutputDC));
            foreach (DataGridViewRow row in dataGridViewTestGPSData.Rows)
            {
               GPSPoint gpsdata = GetGPSData(row);
               gpsdata.Draw(g, Color.Blue);
            }

            if (currGPSData != null)
            {
                currGPSData.Draw(g,Color.Red);
            }
        }

        private GPSPoint currGPSData;
        private void dataGridViewTestGPSData_SelectionChanged(object sender, EventArgs e)
        {
            //Nếu không phải đang tạo dữ liệu test
            if (!isStartTestGPSData)
            {
                if (dataGridViewTestGPSData.CurrentRow != null)
                {
                    currGPSData = GetGPSData(dataGridViewTestGPSData.CurrentRow);
                    mapControl.Map.ZoomTo(mapControl.Map.Zoom, currGPSData.LonGPS, currGPSData.LatGPS);
                    mapControl.Map.Refresh();
                }
            }
        }


    }
}